package cn.mini.mybatis.mybatis.executor;


import cn.mini.mybatis.mybatis.executor.resultset.ResultSetHandler;
import cn.mini.mybatis.mybatis.mapping.BoundSql;
import cn.mini.mybatis.mybatis.mapping.MappedStatement;
import cn.mini.mybatis.mybatis.session.Configuration;
import org.slf4j.LoggerFactory;

import java.sql.SQLException;
import java.sql.Statement;
import java.util.List;


public abstract class BaseExecutor implements Executor {

    private org.slf4j.Logger logger = LoggerFactory.getLogger(BaseExecutor.class);

    protected Configuration configuration;

    protected Executor wrapper;

    private boolean closed;

    protected BaseExecutor(Configuration configuration) {
        this.configuration = configuration;
        this.wrapper = this;
    }


    @Override
    public <E> List<E> query(MappedStatement ms, Object parameter,
                             ResultSetHandler resultHandler, BoundSql boundSql)  {
        if (closed) {
            throw new RuntimeException("Executor was closed.");
        }
        return doQuery(ms, parameter, resultHandler,boundSql);
    }

    protected abstract <E> List<E> doQuery(MappedStatement ms, Object parameter, ResultSetHandler resultHandler, BoundSql boundSql) ;

    @Override
    public int update(MappedStatement ms, Object parameter) throws SQLException {
        // 默认空实现，后续处理
        return 0;
    }

    @Override
    public void commit(boolean required) throws SQLException {
    }

    @Override
    public void rollback(boolean required) throws SQLException {
    }

    @Override
    public void close(boolean forceRollback) {
    }

    protected void closeStatement(Statement statement) {
        if (statement != null) {
            try {
                statement.close();
            } catch (SQLException ignore) {
            }
        }
    }

}
